/* Copyright 2007 Sergejs Melderis (sergey.melderis@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/


package com.sm.binder;


import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.ResultSetMetaData;

/**
 * ColumnBinder maps a ResultSet column to an Object.
 *
 * @author @author Sergejs Melderis (sergey.melderis@gmail.com)
 */
class ColumnBinder {
    private final ColumnValueGetter getter;
    private final Method method;

    /**
     * Constructs ColumnBinder.
     * The parameter ColumnValueGetter getter is used to get a value from ResultSet.
     *
     *
     * @param getter The getter to get a value from ResultSet.
     * @param method Method to invoke with the value that is retrieved from ResultSet
     * using ColumnValueGetter.
     */
    public ColumnBinder(ColumnValueGetter getter, Method method) {
        this.getter = getter;
        this.method = method;
    }

    /**
     * Binds a single column from ResultSet to an Object target.
     * @param rs The ResultSet
     * @param target Object to bind a value from ResultSet.
     * @throws java.sql.SQLException
     */
    public final void bindColumn(ResultSet rs, Object target) throws SQLException {
        Object value;
        try {
            value = getter.getValue(rs);
            method.invoke(target, value);
        } catch (IllegalAccessException e) {
            throw new SQLException(e.getMessage());
        } catch (InvocationTargetException e) {
            throw new SQLException(e.getMessage());
        }
    }


    public Method getMethod() {
        return method;
    }
}


